package com.py.credit.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.Dept;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ResourceModelBindFieldsEnum;
import com.py.credit.service.BusinessModelBindService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.entity.SysOfficeEntity;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 
 * @author tengt
 *
 */
@RestController
@RequestMapping(value="/business")
public class BusinessModelBindController {
	private final static String FRONT_TABLE_ID = "business";
	
    @Autowired
	private BusinessModelBindService businessModelBindService;
    
    @Autowired 
    private XypjRemoteBaseService xypjRemoteBaseService;
    

	/**
	 * @api {get} /modelTest/getTableList.json 获取批次列表
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 表规则管理
	 * 
	 * @apiParam {String} condition 查询条件(可选)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":2,"data":[{"rule_package":"1222","rule_desc":"122222","rule_name":"1","rule_method":"123","id":22,"time":"2018-04-23","managerName":"超级管理员"},{"rule_package":"555","rule_desc":"5555","rule_name":"555","rule_method":"555","id":35,"time":"2018-04-26","managerName":"超级管理员"}]}
	 * 
	 */
	@RequestMapping(value = "/getBindTableList.json")
	public RestServiceResult<List<Map<String, Object>>> getBindTableList(
			@RequestParam(value = "condition", required = false) String condition,
			@RequestParam(value = "officeId", required = false) String officeId,
			@RequestParam(value = "modelName", required = false) String modelName,
			@RequestParam(value = "showScoreLine", required = false) String showScoreLine,
			Page page, HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] additionalColumns = { "id" };
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceModelBindFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
		try {
			List<Map<String, Object>> list = businessModelBindService.getBindByConditionForPage(officeId,modelName,showScoreLine,showColumns, additionalColumns,
					condition, page);
			
			for(Map<String, Object> map:list){
				List<String> alreadyDistributeRecord = businessModelBindService.getAlreadyDistributeRecord(String.valueOf(map.get("id")));
				
				if(alreadyDistributeRecord != null && !alreadyDistributeRecord.isEmpty()){
					String[]  offices = new String[alreadyDistributeRecord.size()];
					
					for(int i = 0; i < alreadyDistributeRecord.size(); i++){
						SysOfficeEntity rootOffice = businessModelBindService.getOfficeById(alreadyDistributeRecord.get(i));
						if(rootOffice != null){
							offices[i] = rootOffice.getOfficeName();
						}
					}
					map.put("bumeng", StringUtils.join(offices, ","));
				}
			}
			r = new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), list);
			
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常！");
		}
		return r;
	}

	/**
	 * 获取批次初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getBindOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getBindOptionalColums() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(ResourceModelBindFieldsEnum.getOptionalColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addBindShowColunms.json")
	public RestServiceResult<String> addBindShowColunms(
			@RequestParam(value = "columns", required = true) String[] columns) {
		RestServiceResult<String> r = new RestServiceResult<String>();
		try {
			MapCache.set(1000 + "_" + FRONT_TABLE_ID, columns);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	@RequestMapping(value = "/getBindAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getBindAdvancedConditionColumns() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(
					ResourceModelBindFieldsEnum.getAdvancedConditionColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}
	
	@RequestMapping(value = "/getBindInfo.json")
	public RestServiceResult<Map<String, Object>> getBindInfo(HttpServletRequest request,String id){
		RestServiceResult<Map<String, Object>> r = new RestServiceResult<>();
		try {
			Map<String, Object> data = businessModelBindService.getBindInfo(id);
		    r.setData(data);
		} catch (Exception e) {
         r.setCode(RestServiceResult.CODE_UNKNOW);
         r.setMsg("系统异常！");
		}
		return r;
	}
	
	@RequestMapping(value = "/insertBindInfo.do")
	public RestServiceResult<Integer> insertBindInfo(HttpServletRequest request,String name,String modelId,String ywId,String showScoreLine
			 ){
		RestServiceResult<Integer> r = new RestServiceResult<>();
		try {
			int  count = businessModelBindService.insertBindInfo(name,modelId,ywId,showScoreLine);
		    r.setData(count);
		} catch (Exception e) {
         r.setCode(RestServiceResult.CODE_UNKNOW);
         r.setMsg("系统异常！");
		}
		return r;
	}
	
	@RequestMapping(value = "/updateBindInfo.do")
	public RestServiceResult<Integer> updateBindInfo(HttpServletRequest request,String name,String modelId,String ywId,String showScoreLine,String id){
		RestServiceResult<Integer> r = new RestServiceResult<>();
		try {
			
			List<String> alreadyDistributeRecord = businessModelBindService.getAlreadyDistributeRecord(id);
			
			for(String deptId :alreadyDistributeRecord ){
				int  count =businessModelBindService.isUpdateDept(modelId,ywId,deptId,id);
				if(count > 0){
					SysOfficeEntity rootOffice = businessModelBindService.getOfficeById(deptId);
					 r.setCode(RestServiceResult.CODE_UNKNOW);
			         r.setMsg("部门"+rootOffice.getOfficeName()+ "已经在相同业务中存在");
			         return r;
				}
			}
			
			int  count = businessModelBindService.updateBindInfo(name,modelId,ywId,showScoreLine,id);
		    r.setData(count);
		} catch (Exception e) {
         r.setCode(RestServiceResult.CODE_UNKNOW);
         r.setMsg("系统异常！");
		}
		return r;
	}
	
	@RequestMapping(value = "/updateBindInfoStatus.do")
	public RestServiceResult<Integer> updateBindInfoStatus(HttpServletRequest request,String id,String status){
		RestServiceResult<Integer> r = new RestServiceResult<>();
		try {
			int count= businessModelBindService.updateBindInfoStatus(id,status);
		    r.setData(count);
		} catch (Exception e) {
         r.setCode(RestServiceResult.CODE_UNKNOW);
         r.setMsg("系统异常！");
		}
		return r;
	}
	
	@RequestMapping(value = "/deleteBindInfo.do")
	public RestServiceResult<Integer> deleteBindInfo(HttpServletRequest request,@RequestParam(value = "ids", defaultValue = "") List<String> ids){
		RestServiceResult<Integer> r = new RestServiceResult<>();
		try {
			int count= businessModelBindService.deleteBindInfo(ids);
		    r.setData(count);
		} catch (Exception e) {
         r.setCode(RestServiceResult.CODE_UNKNOW);
         r.setMsg("系统异常！");
		}
		return r;
	}
	
	@RequestMapping(value = "/distributeDept.json")
	public RestServiceResult<List<SysOfficeEntity>> distributeDept(
			@RequestParam(value = "id", defaultValue = "", required = true) String id) {

		List<SysOfficeEntity> rootOffices = businessModelBindService.getTopLevelDept();

		if (!CollectionUtils.isEmpty(rootOffices)) {

			List<String> alreadyDistributeRecord = businessModelBindService.getAlreadyDistributeRecord(id);

			for (SysOfficeEntity office : rootOffices) {

				for (String officeId : alreadyDistributeRecord) {

					if (officeId != null && officeId.equals(String.valueOf(office.getId()))) {

						office.setChecked(true);
						break;
					}
				}
			}
		}
		return new RestServiceResult<List<SysOfficeEntity>>(rootOffices);
	}
	
	
	@RequestMapping(value = "/distributeCommonResource.json")
	public RestServiceResult<String> distributeCommonResource(
			@RequestParam(value = "dept", defaultValue = "", required = true) String dept,
			@RequestParam(value = "id", defaultValue = "", required = true) String id) {

		List<Map<String, String>> depts = JSON.parseObject(dept, new TypeReference<List<Map<String, String>>>() {});

		//businessModelBindService.isAddDept()
		for(Map<String, String> map: depts){
			int  count =businessModelBindService.isAddDept(String.valueOf(map.get("deptId")), id);
			if(count > 0){
				SysOfficeEntity rootOffice = businessModelBindService.getOfficeById(String.valueOf(map.get("deptId")));
				RestServiceResult<String> r = new RestServiceResult<>();
				 r.setCode(RestServiceResult.CODE_UNKNOW);
		         r.setMsg("部门"+rootOffice.getOfficeName()+ "已经在相同业务中存在");
		         return r;
			}
		}
		
		businessModelBindService.distributeCommonResource(id, depts);

		return new RestServiceResult<String>();

	}
	
	@RequestMapping(value = "/allDept.json")
	public RestServiceResult<List<SysOfficeEntity>> allDept() {

		List<SysOfficeEntity> rootOffices = businessModelBindService.getTopLevelDept();

		return new RestServiceResult<List<SysOfficeEntity>>(rootOffices);
	}
}
